/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reportcenter.recover;

import java.util.TimerTask;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import org.openide.util.Exceptions;
import org.springframework.richclient.util.EventListenerListHelper;
import reportcenter.support.dbutil.JPAFactory;
import reportcenter.support.threading.JobListener;
import reportcenter.support.threading.WorkerJob;

/**
 *
 * @author renan
 */
public class DBBackupExecutor extends TimerTask implements WorkerJob {

    private EventListenerListHelper listeners = new EventListenerListHelper(JobListener.class);
    private final String PATH = System.getProperty("user.home") + "/derby_backup/" + new java.text.SimpleDateFormat("dd-MM-yyyy-hh:mm:ss").format((java.util.Calendar.getInstance()).getTime());

    public void addJobListener(JobListener l) {
        listeners.add(l);
    }

    public void removeJobListener(JobListener l) {
        listeners.remove(l);
    }

    public void run() {
        listeners.fire("start");
        executor();
        listeners.fire("end");
        listeners.fire("status", "Backup efetuado com sucesso em -> " + PATH);
    }

    public boolean executor() {
        boolean ret = false;
        listeners.fire("status", "Processando Backup....");
        listeners.fire("progress", new Integer(20));
        EntityTransaction tx = JPAFactory.getInstance().getManager().getTransaction();
        tx.begin();
        try {
            Query query = JPAFactory.getInstance().getManager().createNativeQuery("CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE('" + PATH + "')");
            query.executeUpdate();
            tx.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            tx.rollback();
        }

        listeners.fire("status", "Efetuando backup da base de dados... acompanhe o progresso no barra ao lado");
        listeners.fire("progress", new Integer(80));
        showMsg();
        return ret;
    }

    private void showMsg() {
        try {
            
            JOptionPane.showMessageDialog(null, "Backup efetuado com sucesso em: " + PATH, "Backup da Base de Dados", JOptionPane.INFORMATION_MESSAGE);
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }
    }
}
